﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DJJuninho.Web.Album.Item
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {


                    int id;
                    if (int.TryParse(Request["id"], out id))
                    {

                        LoadData(id);

                    }

                }

            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void LoadData(int id)
        {
            try
            {

                var obj = new Business.Album(id);

                txtName.Text = obj.Name;
                txtDescription.Text = obj.Description;
                imgPhoto.ImageUrl = ResolveUrl("~/uploads/" + obj.Photo);

            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                Validate();

                if (IsValid)
                {

                    int id;
                    var obj = int.TryParse(Request["id"], out id) ? new Business.Album(id) : new Business.Album();

                    obj.Name = txtName.Text;
                    obj.Description = txtDescription.Text;

                    if (txtPhoto.HasFile)
                    {

                        obj.Photo = DateTime.Now.Ticks + System.IO.Path.GetExtension(txtPhoto.PostedFile.FileName);

                        txtPhoto.PostedFile.SaveAs(Server.MapPath("~/uploads/") + obj.Photo);

                    }

                    obj.Save();

                    Response.Redirect("../");

                }

            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
